package org.budo.support.java.security.util;

import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author lmw
 */
public class DesUtil {
    private static final String DES = "DES";

    private static final String DES_CBC_PKCS5_PADDING = "DES/CBC/PKCS5Padding";

    private static final Logger log = Slf4j.getLogger();

    public static String encrypt(String src, Charset charset, String key) {
        if (null == src || null == charset || null == key) {
            log.error("#26 input null, src=" + src + ", charset=" + charset + ", key=" + key);
            return null;
        }

        try {
            byte[] srcBytes = src.getBytes(charset);
            byte[] encryptBytes = encryptBytes(srcBytes, key);
            return bytesToHexString(encryptBytes);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    public static String decrypt(String hex, Charset charset, String key) {
        if (null == hex || null == charset || null == key) {
            log.error("#41 input null, hex=" + hex + ", charset=" + charset + ", key=" + key);
            return null;
        }

        try {
            byte[] hexBytes = hexStringToBytes(hex);
            byte[] decryptBytes = decryptBytes(hexBytes, key);
            return new String(decryptBytes, charset);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    private static byte[] encryptBytes(byte[] hex, String key) throws Exception {
        Cipher cipher = initCipher(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(hex); // 加密操作
    }

    private static byte[] decryptBytes(byte[] src, String key) throws Exception {
        Cipher cipher = initCipher(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(src); // 解密操作
    }

    private static Cipher initCipher(int mode, String key) throws Exception {
        byte[] keyBytes = key.getBytes();

        IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes); // 初始化向量
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);

        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(DES); // 创建一个密匙工厂，然后用它把DESKeySpec转换成securekey
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance(DES_CBC_PKCS5_PADDING); // Cipher对象实际完成加密操作
        cipher.init(mode, secretKey, ivParameterSpec); // 用密匙初始化Cipher对象
        return cipher;
    }

    private static String bytesToHexString(byte buf[]) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            stringBuffer.append(hex.toUpperCase());
        }
        return stringBuffer.toString();
    }

    private static byte[] hexStringToBytes(String hex) {
        if (null == hex || hex.length() < 1) {
            return null;
        }

        byte[] result = new byte[hex.length() / 2];
        for (int i = 0; i < hex.length() / 2; i++) {
            String highStr = hex.substring(i * 2, i * 2 + 1);
            int high = Integer.parseInt(highStr, 16);

            String lowStr = hex.substring(i * 2 + 1, i * 2 + 2);
            int low = Integer.parseInt(lowStr, 16);
            result[i] = (byte) (high * 16 + low);
        }

        return result;
    }
}